'use client';

import React, { useState, useEffect, useRef } from 'react';
import http from '@/lib/request';

// 自定义消息提示组件
const Toast = ({ message, type = 'info' }: { message: string; type?: 'info' | 'success' | 'error' }) => {
  const bgColor = {
    info: 'bg-blue-500',
    success: 'bg-green-500',
    error: 'bg-red-500'
  };

  return (
    <div className={`fixed top-4 right-4 px-4 py-2 rounded-lg text-white shadow-lg ${bgColor[type]} z-50`}>
      {message}
    </div>
  );
};

// 自定义确认对话框组件
const ConfirmModal = ({ 
  title, 
  content, 
  onOk, 
  onCancel, 
  visible 
}: { 
  title: string;
  content: string;
  onOk: () => void;
  onCancel: () => void;
  visible: boolean;
}) => {
  if (!visible) return null;

  return (
    <div className="fixed inset-0 flex items-center justify-center bg-black bg-opacity-50 z-50">
      <div className="bg-white rounded-lg p-6 w-full max-w-md">
        <h3 className="text-xl font-bold mb-4">{title}</h3>
        <p className="mb-6">{content}</p>
        <div className="flex justify-end gap-3">
          <button 
            onClick={onCancel}
            className="px-4 py-2 border border-gray-300 rounded-md hover:bg-gray-50"
          >
            取消
          </button>
          <button 
            onClick={onOk}
            className="px-4 py-2 bg-red-500 text-white rounded-md hover:bg-red-600"
          >
            删除
          </button>
        </div>
      </div>
    </div>
  );
};

// 自定义按钮组件
const Button = ({ 
  type = 'default', 
  onClick, 
  children, 
  icon, 
  className = '' 
}: { 
  type?: 'default' | 'primary' | 'danger';
  onClick?: () => void;
  children: React.ReactNode;
  icon?: React.ReactNode;
  className?: string;
}) => {
  const baseClasses = 'px-4 py-2 rounded-md font-medium flex items-center gap-2 transition-colors';
  const typeClasses = {
    default: 'bg-white text-gray-700 border border-gray-300 hover:bg-gray-50',
    primary: 'bg-blue-500 text-white hover:bg-blue-600',
    danger: 'bg-red-500 text-white hover:bg-red-600'
  };

  return (
    <button 
      onClick={onClick}
      className={`${baseClasses} ${typeClasses[type]} ${className}`}
    >
      {icon}
      {children}
    </button>
  );
};

// 自定义输入框组件
const Input = ({ 
  value, 
  onChange, 
  placeholder = '', 
  type = 'text', 
  error = '',
  name = ''
}: { 
  value: string;
  onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
  placeholder?: string;
  type?: 'text' | 'password' | 'email';
  error?: string;
  name?: string;
}) => {
  return (
    <div className="mb-4">
      <input
        name={name}
        type={type}
        value={value}
        onChange={onChange}
        placeholder={placeholder}
        className={`w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 ${error ? 'border-red-500' : 'border-gray-300'}`}
      />
      {error && <p className="text-red-500 text-sm mt-1">{error}</p>}
    </div>
  );
};

// 自定义模态框组件
const Modal = ({ 
  title, 
  visible, 
  onCancel, 
  onOk, 
  children 
}: { 
  title: string;
  visible: boolean;
  onCancel: () => void;
  onOk: () => void;
  children: React.ReactNode;
}) => {
  if (!visible) return null;

  return (
    <div className="fixed inset-0 flex items-center justify-center bg-black bg-opacity-50 z-50">
      <div className="bg-white rounded-lg p-6 w-full max-w-md">
        <div className="flex justify-between items-center mb-4">
          <h3 className="text-xl font-bold">{title}</h3>
          <button 
            onClick={onCancel}
            className="text-gray-500 hover:text-gray-700"
          >
            ✕
          </button>
        </div>
        <div className="mb-6">
          {children}
        </div>
        <div className="flex justify-end gap-3">
          <button 
            onClick={onCancel}
            className="px-4 py-2 border border-gray-300 rounded-md hover:bg-gray-50"
          >
            取消
          </button>
          <button 
            onClick={onOk}
            className="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600"
          >
            保存
          </button>
        </div>
      </div>
    </div>
  );
};

interface User {
  id: number;
  username: string;
  password_hash: string;
  email?: string;
  created_at?: string;
}

const UserManagement: React.FC = () => {
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(false);
  const [editingUser, setEditingUser] = useState<User | null>(null);
  const [toast, setToast] = useState<{ visible: boolean; message: string; type: 'info' | 'success' | 'error' }>({ visible: false, message: '', type: 'info' });
  const [confirmVisible, setConfirmVisible] = useState<boolean>(false);
  const [userToDelete, setUserToDelete] = useState<User | null>(null);
  const [formErrors, setFormErrors] = useState<{ username?: string; password_hash?: string; email?: string }>({});
  const [formValues, setFormValues] = useState<{ username: string; password_hash: string; email: string }>({
    username: '',
    password_hash: '',
    email: ''
  });

  // 显示消息提示
  const showToast = (message: string, type: 'info' | 'success' | 'error' = 'info') => {
    setToast({ visible: true, message, type });
    setTimeout(() => setToast({ ...toast, visible: false }), 3000);
  };

  // 表单验证
  const validateForm = () => {
    const errors: { username?: string; password_hash?: string; email?: string } = {};
    
    if (!formValues.username.trim()) {
      errors.username = '请输入用户名';
    }

    if (!editingUser && !formValues.password_hash.trim()) {
      errors.password_hash = '请输入密码';
    }

    if (formValues.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formValues.email)) {
      errors.email = '请输入有效的邮箱地址';
    }

    setFormErrors(errors);
    return Object.keys(errors).length === 0;
  };

  // 获取用户列表
  const fetchUsers = async () => {
    setLoading(true);
    try {
      const res = await http.get<User[]>('/api/users');
      if (res.code === 0) {
        setUsers(res.data);
      } else {
        showToast(res.msg || '获取用户列表失败', 'error');
      }
    } catch (error) {
      console.error('获取用户列表失败:', error);
      showToast('获取用户列表失败', 'error');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchUsers();
  }, []);

  // 打开添加用户模态框
  const handleAdd = () => {
    setEditingUser(null);
    setFormValues({ username: '', password_hash: '', email: '' });
    setFormErrors({});
    setVisible(true);
  };

  // 打开编辑用户模态框
  const handleEdit = (user: User) => {
    setEditingUser(user);
    setFormValues({ 
      username: user.username, 
      password_hash: '', 
      email: user.email || '' 
    });
    setFormErrors({});
    setVisible(true);
  };

  // 确认删除用户
  const handleDeleteConfirm = (user: User) => {
    setUserToDelete(user);
    setConfirmVisible(true);
  };

  const handleDelete = async () => {
    if (!userToDelete) return;

    try {
      const res = await http.delete(`/api/users/${userToDelete.id}`);
      if (res.code === 0) {
        showToast('删除用户成功', 'success');
        fetchUsers();
      } else {
        showToast(res.msg || '删除用户失败', 'error');
      }
    } catch (error) {
      console.error('删除用户失败:', error);
      showToast('删除用户失败', 'error');
    } finally {
      setConfirmVisible(false);
      setUserToDelete(null);
    }
  };

  // 提交表单
  const handleSubmit = async () => {
    if (!validateForm()) return;

    try {
      const requestData = { ...formValues };
      
      // 如果是编辑且密码为空，不发送密码字段
      if (editingUser && !requestData.password_hash) {
        (requestData as Partial<typeof requestData>).password_hash = undefined;
      }

      let res;
      if (editingUser) {
        res = await http.put(`/api/users/${editingUser.id}`, requestData);
      } else {
        res = await http.post('/api/users', requestData);
      }
      
      if (res.code === 0) {
        showToast(editingUser ? '更新用户成功' : '添加用户成功', 'success');
        setVisible(false);
        setFormValues({ username: '', password_hash: '', email: '' });
        setFormErrors({});
        setEditingUser(null);
        fetchUsers();
      } else {
        showToast(res.msg || (editingUser ? '更新用户失败' : '添加用户失败'), 'error');
      }
    } catch (error) {
      console.error('提交表单失败:', error);
      showToast('提交表单失败', 'error');
    }
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormValues(prev => ({ ...prev, [name]: value }));
    
    // 清除对应字段的错误信息
    if (formErrors[name as keyof typeof formErrors]) {
      setFormErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors[name as keyof typeof formErrors];
        return newErrors;
      });
    }
  };

  return (
    <div className="p-6">
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-2xl font-bold">用户管理</h1>
        <Button
          type="primary"
          icon="➕"
          onClick={handleAdd}
        >
          添加用户
        </Button>
      </div>

      {/* 用户列表表格 */}
      <div className="overflow-x-auto">
        <table className="min-w-full bg-white border border-gray-200 rounded-lg">
          <thead>
            <tr className="bg-gray-50">
              <th className="py-2 px-4 border-b text-left text-sm font-medium text-gray-700">ID</th>
              <th className="py-2 px-4 border-b text-left text-sm font-medium text-gray-700">用户名</th>
              <th className="py-2 px-4 border-b text-left text-sm font-medium text-gray-700">邮箱</th>
              <th className="py-2 px-4 border-b text-left text-sm font-medium text-gray-700">创建时间</th>
              <th className="py-2 px-4 border-b text-left text-sm font-medium text-gray-700">操作</th>
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <tr>
                <td colSpan={5} className="py-4 text-center">加载中...</td>
              </tr>
            ) : users.length === 0 ? (
              <tr>
                <td colSpan={5} className="py-4 text-center">暂无用户数据</td>
              </tr>
            ) : (
              users.map(user => (
                <tr key={user.id} className="hover:bg-gray-50">
                  <td className="py-2 px-4 border-b">{user.id}</td>
                  <td className="py-2 px-4 border-b">{user.username}</td>
                  <td className="py-2 px-4 border-b">{user.email || '-'}</td>
                  <td className="py-2 px-4 border-b">{user.created_at ? new Date(user.created_at).toLocaleString() : '-'}</td>
                  <td className="py-2 px-4 border-b">
                    <div className="flex gap-2">
                      <Button
                        type="primary"
                        icon="✏️"
                        onClick={() => handleEdit(user)}
                        className="text-blue-600 hover:text-blue-800 hover:bg-blue-50"
                      >
                        编辑
                      </Button>
                      <Button
                        type="danger"
                        icon="🗑️"
                        onClick={() => handleDeleteConfirm(user)}
                        className="text-red-600 hover:text-red-800 hover:bg-red-50"
                      >
                        删除
                      </Button>
                    </div>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>

      {/* 添加/编辑用户模态框 */}
      <Modal
        title={editingUser ? '编辑用户' : '添加用户'}
        visible={visible}
        onCancel={() => setVisible(false)}
        onOk={handleSubmit}
      >
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">用户名</label>
            <Input
              name="username"
              value={formValues.username}
              onChange={handleInputChange}
              placeholder="请输入用户名"
              error={formErrors.username}
            />
          </div>

          {!editingUser && (
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">密码</label>
              <Input
                name="password_hash"
                type="password"
                value={formValues.password_hash}
                onChange={handleInputChange}
                placeholder="请输入密码"
                error={formErrors.password_hash}
              />
            </div>
          )}

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">邮箱</label>
            <Input
              name="email"
              type="email"
              value={formValues.email}
              onChange={handleInputChange}
              placeholder="请输入邮箱"
              error={formErrors.email}
            />
          </div>
        </div>
      </Modal>

      {/* 确认删除对话框 */}
      <ConfirmModal
        title="确认删除"
        content={`确定要删除用户 ${userToDelete?.username} 吗？`}
        onOk={handleDelete}
        onCancel={() => setConfirmVisible(false)}
        visible={confirmVisible}
      />

      {/* 消息提示 */}
      {toast.visible && <Toast message={toast.message} type={toast.type} />}
    </div>
  );
};

export default UserManagement;